import React from 'react';
import { connect } from 'react-redux';
import { bindActionCreators, Dispatch } from 'redux';
import { Button, Input, Modal } from 'antd';
import { getStorageManager } from '@/services/storage';
import AnthropicService, { NO_ANTHROPIC_API_KEY_ERROR } from '@/services/anthropic/anthropic.service';
import { Actions as simpleActions } from '@/actions/simple_actions';
import * as actions from '@/actions';
import { State } from '@/reducers/state';
import { message } from 'antd';

export interface AiTabProps {
    config: { [key: string]: any };
    updateConfig: (config: { [key: string]: any }) => void;
}

interface AiTabAppState {
    anthropicAPIKey: string;
    prompt: string;
    promptResponse: string;
    error: string;
}

class AITab extends React.Component<AiTabProps, AiTabAppState> {
    constructor(props: any) {
        super(props);
        this.onClickTestPrompt = this.onClickTestPrompt.bind(this);
    }

    state: AiTabAppState = {
        anthropicAPIKey: '',
        prompt: 'Explain a random RPA IDE 命令',
        promptResponse: '',
        error: '',
    };

    async onClickTestPrompt() {
        console.log('anthropicAPIKey:>> ', this.props.config.anthropicAPIKey);

        const anthropicAPIKey = this.props.config.anthropicAPIKey || '';
        if (!anthropicAPIKey) {
            message.error(NO_ANTHROPIC_API_KEY_ERROR);
            return;
        }

        const anthropicService = new AnthropicService(this.props.config.anthropicAPIKey);

        anthropicService
            ?.getPromptResponse(this.state.prompt)
            .then((response) => {
                this.setState({ promptResponse: response });
                this.setState({ error: '' });
            })
            .catch((error) => {
                console.error('Error getting response:', error);
                // this.setState({ error: error.message })
                message.error(error.message);
            });
    }

    render() {
        const onConfigChange = (key: string, val: string) => {
            this.props.updateConfig({ [key]: val });
        };

        return (
            <div className='ai-tab'>
                <div
                    className='row'
                    style={{ marginBottom: '20px' }}
                >
                    AI 命令功能目前处于实验/测试阶段。它使用 Anthropic API。要启用 AI 命令，请在下面输入您的（免费）Anthropic API 密钥
                    {/* <a
                         href="https://goto.ui.vision/x/idehelp?help=ai"
                        target='_blank'
                    >
                        （更多信息）
                    </a> */}
                    :
                </div>

                <div className='ai-settings-item'>
                    <span className='label-text'>API 密钥:</span>
                    <Input
                        type='text'
                        value={this.state.anthropicAPIKey}
                        onChange={(e) => {
                            this.setState({ anthropicAPIKey: e.target.value });
                        }}
                    />
                    <Button
                        type='primary'
                        onClick={() => {
                            if (this.props.config.anthropicAPIKey) {
                                Modal.confirm({
                                    title: 'Confirm',
                                    content: '是否覆盖现有的API密钥？',
                                    okText: 'Yes',
                                    cancelText: 'No',
                                    onOk: () => {
                                        onConfigChange('anthropicAPIKey', this.state.anthropicAPIKey);
                                        this.setState({ anthropicAPIKey: '' });
                                    },
                                });
                            } else {
                                onConfigChange('anthropicAPIKey', this.state.anthropicAPIKey);
                                this.setState({ anthropicAPIKey: '' });
                            }
                        }}
                        // disabled={this.state.anthropicAPIKey === this.props.config.anthropicAPIKey}
                    >
                        保存
                    </Button>
                </div>
                <div className='ai-settings-item'>
                    <span className='label-text'>Prompt:</span>
                    <Input
                        type='text'
                        value={this.state.prompt || 'Hello Claude'} //is this text used anywhere?
                        onChange={(e) => {
                            this.setState({ prompt: e.target.value });
                        }}
                    />
                    <Button
                        type='primary'
                        onClick={this.onClickTestPrompt}
                    >
                        测试
                    </Button>
                    {/* <Button type="primary" onClick={this.onClickTestFindImageCenter}>
            Test Image
          </Button> */}
                </div>
                <div
                    className='row'
                    style={{ marginBottom: '10px' }}
                >
                    Anthropic API (Claude) 回答:
                </div>
                <div className='ai-response'>
                    <pre>{this.state.promptResponse}</pre>
                </div>
                <div className='ai-settings-item'>
                    <span className='label-text'>
                        <strong>aiComputerUse命令：</strong>停止前的最大循环次数：
                    </span>
                    <Input
                        type='number'
                        min='0'
                        style={{ marginLeft: '10px', width: '70px' }}
                        value={this.props.config.aiComputerUseMaxLoops}
                        onChange={(e) => onConfigChange('aiComputerUseMaxLoops', e.target.value)}
                        placeholder='20'
                    />
                </div>
                <div
                    className='row'
                    style={{ marginBottom: '10px', color: 'red' }}
                >
                    {this.state.error}
                </div>
            </div>
        );
    }
}

export default connect(
    (state: State) => ({
        status: state.status,
        config: state.config,
    }),
    (dispatch: Dispatch) => bindActionCreators({ ...actions, ...simpleActions }, dispatch)
)(AITab);
